package com.huaao.micropolice.root.controllers.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.huaao.micropolice.common.util.JsonUtil;
import com.huaao.micropolice.core.model.system.Area;
import com.huaao.micropolice.core.model.system.Button;
import com.huaao.micropolice.core.service.system.AreaService;
import com.huaao.micropolice.core.service.system.impl.AreaServiceImpl;
import com.huaao.micropolice.root.controllers.BaseController;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

@Controller
@RequestMapping("system/area")
public class AreaController extends BaseController {
	@Autowired
	private AreaService areaService;
	private static JsonConfig jsonConfig = new JsonConfig();
	private static JsonConfig ztreeConfig = new JsonConfig();
	static{
		ztreeConfig.setExcludes(new String[]{"children","parent","state","type","handler","hibernateLazyInitializer"});
	}
 
	@RequestMapping("index.do")
	public String index() {
		return "/system/area/index";
	}
	
	@RequestMapping("save.do")
	public ResponseEntity<String> save(Area item) {
		if(StringUtils.isEmpty(item.getId())){
			areaService.save(item);
		}else{
			areaService.update(item);
		}
		return super.ajaxModel(JSON, JsonUtil.toJson(successMap()));
	}
	
	@RequestMapping("del.do")
	public ResponseEntity<String> del(String id) {
		try {
			areaService.del(id);
			return super.ajaxModel(JSON, JsonUtil.toJson(successMap()));
		} catch (Exception e) {
			return super.ajaxModel(JSON, JsonUtil.toJson(failMap(e.getMessage())));
		}
	}
	
	@RequestMapping(value="findListJson.do",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String findListJson(String nodeid){
		List<Area> list = areaService.findByAreaParentId(nodeid);
		String result = JSONArray.fromObject(list.toArray(),ztreeConfig).toString();
		return result;
	}
	
	@RequestMapping(value="findAllJson.do",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String findAllJson(){
		List<Area> list = areaService.findAll();
		String result = JSONArray.fromObject(list.toArray(),ztreeConfig).toString();
		return result;
	}
}
